package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	global2 "longmen/server/config/global"
	"longmen/server/internal/services/nami/config"
	"longmen/server/pkg/db/mysql/models/models_sports"
)

func unique(intSlice []string) []string {
	keys := make(map[string]bool)
	var list []string
	for _, entry := range intSlice {
		if _, value := keys[entry]; !value {
			keys[entry] = true
			list = append(list, entry)
		}
	}
	return list
}

var flashComp = &cobra.Command{
	Use:   "flash_comp",
	Short: "刷新联赛名简称",
	Long:  "添加了新的字段，数据需要重新滚一遍",
	Run: func(cmd *cobra.Command, args []string) {
		data := make([]models_sports.MatchTempSchedule, 0)
		err := global2.Sport().Where("comp_short_zh = ''").Find(&data).Error
		if err == nil {
			ftCompName := make([]string, 0)
			btCompName := make([]string, 0)
			for _, item := range data {
				if item.SportId == 1 {
					ftCompName = append(ftCompName, item.Comp)
				} else {
					btCompName = append(btCompName, item.Comp)
				}
			}
			// comp > comp_short_name
			realNameMap := make(map[string]string)

			ftCompName = unique(ftCompName)
			btCompName = unique(btCompName)

			ftData := make([]models_sports.FootballCompetition, 0)
			global2.Sport().Where("name_zh in ?", ftCompName).Find(&ftData)

			if len(ftData) > 0 {
				for _, datum := range ftData {
					realNameMap[datum.NameZh] = datum.ShortNameZh
				}
			}

			btData := make([]models_sports.BasketballCompetition, 0)
			global2.Sport().Where("name_zh in ?", btCompName).Find(&btData)

			if len(btData) > 0 {
				for _, datum := range btData {
					realNameMap[datum.NameZh] = datum.ShortNameZh
				}
			}
			updateMap := make(map[int]string)
			for _, item := range data {
				shortName, ok := realNameMap[item.Comp]
				if !ok {
					continue
				}
				//item.CompShortZh = shortName
				//global.Sport().Model(data[i]).Update("comp_short_zh", shortName)
				updateMap[item.Id] = shortName
			}
			bulkStandardUpdate(updateMap)
		}
	},
	PreRun: func(cmd *cobra.Command, args []string) {
		global2.Initialize(configFile)
		config.InitConfig()
	},
	PostRun: func(cmd *cobra.Command, args []string) {

	},
}

func bulkStandardUpdate(nameMap map[int]string) {
	core := ""
	ids := make([]int, 0)
	for id, name := range nameMap {
		core += fmt.Sprintf("WHEN '%d' THEN '%s' ", id, name)
		ids = append(ids, id)
	}
	if len(ids) == 0 {
		global2.Log.Error("没有数据需要更新")
		return
	}
	sql := fmt.Sprintf("UPDATE `db_matches_schedule` SET `comp_short_zh`= CASE `id` %s END WHERE `id` IN (?)", core)
	//fmt.Println(sql)
	tx := global2.Sport().Begin()

	err := tx.Exec(sql, ids).Error
	if err == nil {
		tx.Commit()
	} else {
		tx.Rollback()
	}
}
